<template>
  <div class="contract-management">
    <div class="header">
      <div class="header-content">
        <router-link class="back-btn" to="/main/renshi/employee/process">
          <i class="el-icon-arrow-left"></i>
          <span>返回</span>
        </router-link>
        <h2 class="page-title">合同管理</h2>
      </div>
    </div>

    <div class="content">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="left">
          <el-button type="primary" icon="el-icon-plus" @click="openContractDialog">新增合同</el-button>
          <el-button type="warning" icon="el-icon-bell" @click="showExpiringContracts">
            即将到期
            <el-badge v-if="expiringCount > 0" :value="expiringCount" class="expiring-badge"></el-badge>
          </el-button>
        </div>
        <div class="right">
          <el-input
            v-model="searchQuery"
            placeholder="搜索合同编号/员工姓名"
            prefix-icon="el-icon-search"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
            style="width: 250px">
          </el-input>
          <el-select v-model="statusFilter" placeholder="合同状态" clearable @change="handleSearch" style="width: 120px; margin-left: 10px">
            <el-option label="生效中" value="active"></el-option>
            <el-option label="已到期" value="expired"></el-option>
            <el-option label="待生效" value="pending"></el-option>
            <el-option label="已终止" value="terminated"></el-option>
          </el-select>
        </div>
      </div>

      <!-- 合同列表 -->
      <el-table
        :data="contractList"
        style="width: 100%"
        border
        v-loading="loading">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="contract-expand">
              <el-form-item label="合同详情">
                <span>{{ props.row.details }}</span>
              </el-form-item>
              <el-form-item label="试用期">
                <span>{{ props.row.probationPeriod }}个月</span>
              </el-form-item>
              <el-form-item label="保密协议">
                <el-tag size="small" :type="props.row.hasNDA ? 'success' : 'danger'">
                  {{ props.row.hasNDA ? '已签署' : '未签署' }}
                </el-tag>
              </el-form-item>
              <el-form-item label="竞业限制">
                <el-tag size="small" :type="props.row.hasNonCompete ? 'success' : 'info'">
                  {{ props.row.hasNonCompete ? '有' : '无' }}
                </el-tag>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="contractNo" label="合同编号" width="180">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewContract(scope.row)">{{ scope.row.contractNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="employeeName" label="员工姓名" width="120"></el-table-column>
        <el-table-column prop="department" label="所属部门" width="120"></el-table-column>
        <el-table-column prop="type" label="合同类型" width="120">
          <template slot-scope="scope">
            {{ getContractType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120"></el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120"></el-table-column>
        <el-table-column prop="duration" label="合同期限" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.duration }}年</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="viewContract(scope.row)">查看</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="editContract(scope.row)"
              :disabled="!canEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="success"
              @click="renewContract(scope.row)"
              v-if="canRenew(scope.row)">续签</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="terminateContract(scope.row)"
              v-if="canTerminate(scope.row)">终止</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 合同表单对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增合同' : dialogType === 'edit' ? '编辑合同' : '续签合同'"
      :visible.sync="dialogVisible"
      width="60%"
      @close="handleDialogClose">
      <el-form :model="contractForm" :rules="contractRules" ref="contractForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工" prop="employeeId">
              <el-select
                v-model="contractForm.employeeId"
                filterable
                remote
                :remote-method="searchEmployees"
                :loading="employeesLoading"
                placeholder="请选择员工"
                :disabled="dialogType === 'edit'">
                <el-option
                  v-for="emp in employees"
                  :key="emp.id"
                  :label="emp.name"
                  :value="emp.id">
                  <span style="float: left">{{ emp.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ emp.department }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="type">
              <el-select v-model="contractForm.type" placeholder="请选择">
                <el-option label="固定期限" value="fixed"></el-option>
                <el-option label="无固定期限" value="unlimited"></el-option>
                <el-option label="实习" value="internship"></el-option>
                <el-option label="试用期" value="probation"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="contractForm.startDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="contractForm.endDate"
                type="date"
                placeholder="选择日期"
                :disabled="contractForm.type === 'unlimited'"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试用期" prop="probationPeriod">
              <el-input-number
                v-model="contractForm.probationPeriod"
                :min="0"
                :max="6"
                placeholder="月">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保密协议" prop="hasNDA">
              <el-switch v-model="contractForm.hasNDA"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="竞业限制" prop="hasNonCompete">
              <el-switch v-model="contractForm.hasNonCompete"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="合同附件" prop="attachment">
              <el-upload
                class="contract-upload"
                action="#"
                :auto-upload="false"
                :file-list="contractForm.attachment"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传 pdf 文件，且不超过 10MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                v-model="contractForm.remark"
                :rows="3"
                placeholder="请输入备注信息">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitContract" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 合同详情对话框 -->
    <el-dialog title="合同详情" :visible.sync="detailVisible" width="60%">
      <el-descriptions class="margin-top" title="基本信息" :column="3" border>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            员工姓名
          </template>
          {{ currentContract.employeeName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-tickets"></i>
            合同编号
          </template>
          {{ currentContract.contractNo }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-office-building"></i>
            所属部门
          </template>
          {{ currentContract.department }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-date"></i>
            开始日期
          </template>
          {{ currentContract.startDate }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-date"></i>
            结束日期
          </template>
          {{ currentContract.endDate || '无固定期限' }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-time"></i>
            合同期限
          </template>
          {{ currentContract.duration }}年
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-warning"></i>
            试用期
          </template>
          {{ currentContract.probationPeriod }}个月
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-lock"></i>
            保密协议
          </template>
          <el-tag size="small" :type="currentContract.hasNDA ? 'success' : 'danger'">
            {{ currentContract.hasNDA ? '已签署' : '未签署' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-lock"></i>
            竞业限制
          </template>
          <el-tag size="small" :type="currentContract.hasNonCompete ? 'success' : 'info'">
            {{ currentContract.hasNonCompete ? '有' : '无' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">合同附件</el-divider>
      <div class="attachment-list">
        <div v-for="(file, index) in currentContract.attachment" :key="index" class="attachment-item">
          <i class="el-icon-document"></i>
          <span class="file-name">{{ file.name }}</span>
          <el-button type="text" @click="downloadFile(file)">下载</el-button>
          <el-button type="text" @click="previewFile(file)">预览</el-button>
        </div>
      </div>

      <el-divider content-position="left">备注信息</el-divider>
      <p class="remark-text">{{ currentContract.remark || '暂无备注' }}</p>

      <el-divider content-position="left">操作记录</el-divider>
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in currentContract.activities"
          :key="index"
          :timestamp="activity.timestamp"
          :type="activity.type">
          {{ activity.content }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 终止合同对话框 -->
    <el-dialog title="终止合同" :visible.sync="terminateVisible" width="40%">
      <el-form :model="terminateForm" :rules="terminateRules" ref="terminateForm" label-width="100px">
        <el-form-item label="终止日期" prop="terminateDate">
          <el-date-picker
            v-model="terminateForm.terminateDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="终止原因" prop="reason">
          <el-select v-model="terminateForm.reason" placeholder="请选择终止原因">
            <el-option label="员工主动离职" value="resignation"></el-option>
            <el-option label="公司解聘" value="dismissal"></el-option>
            <el-option label="协商解除" value="mutual"></el-option>
            <el-option label="其他原因" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="补充说明" prop="remark">
          <el-input
            type="textarea"
            v-model="terminateForm.remark"
            :rows="3"
            placeholder="请输入补充说明">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="terminateVisible = false">取 消</el-button>
        <el-button type="danger" @click="confirmTerminate" :loading="submitting">确认终止</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog title="文件预览" :visible.sync="previewVisible" width="80%" class="preview-dialog">
      <div class="preview-container">
        <iframe :src="previewUrl" frameborder="0"></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ContractManagement',
  data() {
    return {
      loading: false,
      submitting: false,
      employeesLoading: false,
      searchQuery: '',
      statusFilter: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      expiringCount: 0,
      contractList: [],
      employees: [],
      dialogVisible: false,
      dialogType: 'add',
      detailVisible: false,
      terminateVisible: false,
      currentContract: {},
      contractForm: {
        employeeId: '',
        type: '',
        startDate: '',
        endDate: '',
        probationPeriod: 0,
        hasNDA: false,
        hasNonCompete: false,
        attachment: [],
        remark: ''
      },
      terminateForm: {
        terminateDate: '',
        reason: '',
        remark: ''
      },
      contractRules: {
        employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
        type: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
        startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
      },
      terminateRules: {
        terminateDate: [{ required: true, message: '请选择终止日期', trigger: 'change' }],
        reason: [{ required: true, message: '请选择终止原因', trigger: 'change' }]
      },
      previewVisible: false,
      previewUrl: '',
      expiringCount: 0,
      employeesLoading: false,
      terminateReasons: [
        { label: '员工主动离职', value: 'resignation' },
        { label: '公司解聘', value: 'dismissal' },
        { label: '协商解除', value: 'mutual' },
        { label: '其他原因', value: 'other' }
      ],
      contractTypes: [
        { label: '固定期限', value: 'fixed' },
        { label: '无固定期限', value: 'unlimited' },
        { label: '实习', value: 'internship' },
        { label: '试用期', value: 'probation' }
      ]
    }
  },
  methods: {
    getContractType(type) {
      const typeMap = {
        fixed: '固定期限',
        unlimited: '无固定期限',
        internship: '实习',
        probation: '试用期'
      }
      return typeMap[type] || type
    },
    getStatusType(status) {
      const statusMap = {
        active: 'success',
        expired: 'danger',
        pending: 'warning',
        terminated: 'info'
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        active: '生效中',
        expired: '已到期',
        pending: '待生效',
        terminated: '已终止'
      }
      return statusMap[status] || status
    },
    canEdit(contract) {
      return ['pending', 'active'].includes(contract.status)
    },
    canRenew(contract) {
      return contract.status === 'active' && contract.type !== 'unlimited'
    },
    canTerminate(contract) {
      return contract.status === 'active'
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchContractList()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchContractList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchContractList()
    },
    handleFileChange(file) {
      // 处理文件上传
    },
    handleFileRemove(file) {
      // 处理文件移除
    },
    handleDialogClose() {
      this.$refs.contractForm?.resetFields()
      this.contractForm = {
        employeeId: '',
        type: '',
        startDate: '',
        endDate: '',
        probationPeriod: 0,
        hasNDA: false,
        hasNonCompete: false,
        attachment: [],
        remark: ''
      }
    },
    async searchEmployees(query) {
      if (query) {
        this.employeesLoading = true
        try {
          // TODO: 调用接口搜索员工
          await new Promise(resolve => setTimeout(resolve, 500))
          this.employees = [
            { id: 1, name: '张三', department: '技术部' },
            { id: 2, name: '李四', department: '人事部' }
          ]
        } finally {
          this.employeesLoading = false
        }
      }
    },
    async fetchContractList() {
      this.loading = true
      try {
        // TODO: 调用接口获取合同列表
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.contractList = []
        this.total = 0
      } catch (error) {
        this.$message.error('获取合同列表失败')
      } finally {
        this.loading = false
      }
    },
    showExpiringContracts() {
      this.statusFilter = 'expiring'
      this.handleSearch()
    },
    openContractDialog(type = 'add') {
      this.dialogType = type
      this.dialogVisible = true
    },
    async submitContract() {
      try {
        await this.$refs.contractForm.validate()
        this.submitting = true
        // TODO: 调用接口保存合同
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.$message.success('操作成功')
        this.dialogVisible = false
        this.fetchContractList()
      } catch (error) {
        console.error(error)
        this.$message.error('表单验证失败')
      } finally {
        this.submitting = false
      }
    },
    viewContract(contract) {
      this.currentContract = { ...contract }
      this.detailVisible = true
    },
    editContract(contract) {
      this.contractForm = { ...contract }
      this.dialogType = 'edit'
      this.dialogVisible = true
    },
    renewContract(contract) {
      this.contractForm = {
        ...contract,
        startDate: contract.endDate,
        endDate: ''
      }
      this.dialogType = 'renew'
      this.dialogVisible = true
    },
    terminateContract(contract) {
      this.currentContract = contract
      this.terminateVisible = true
    },
    async confirmTerminate() {
      try {
        await this.$refs.terminateForm.validate()
        this.submitting = true
        // TODO: 调用接口终止合同
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.$message.success('合同已终止')
        this.terminateVisible = false
        this.fetchContractList()
      } catch (error) {
        console.error(error)
        this.$message.error('操作失败')
      } finally {
        this.submitting = false
      }
    },
    async fetchExpiringCount() {
      try {
        // TODO: 调用接口获取即将到期的合同数量
        const response = await this.$http.get('/api/contracts/expiring/count')
        this.expiringCount = response.data
      } catch (error) {
        console.error('获取即将到期合同数量失败:', error)
      }
    },
    beforeUpload(file) {
      const isPDF = file.type === 'application/pdf'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isPDF) {
        this.$message.error('只能上传 PDF 文件!')
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!')
      }
      return isPDF && isLt10M
    },
    previewFile(file) {
      // 这里可以根据实际情况处理文件预览
      // 可以使用 PDF.js 或其他预览工具
      this.previewUrl = URL.createObjectURL(file.raw)
      this.previewVisible = true
    },
    async downloadFile(file) {
      try {
        const response = await this.$http.get(`/api/contracts/files/${file.id}`, {
          responseType: 'blob'
        })
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', file.name)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } catch (error) {
        this.$message.error('文件下载失败')
      }
    },
    exportContracts() {
      // 实现导出合同列表的功能
    }
  },
  created() {
    this.fetchContractList()
    this.fetchExpiringCount()
  }
}
</script>

<style lang="scss" scoped>
.contract-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);

  .header {
    margin-bottom: 20px;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    
    .header-content {
      position: relative;
      text-align: center;

      .back-btn {
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        text-decoration: none;
        color: #606266;
        display: flex;
        align-items: center;

        &:hover {
          color: #409EFF;
        }

        i {
          margin-right: 5px;
        }
      }

      .page-title {
        margin: 0;
        font-size: 24px;
        color: #303133;
      }
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);

    .toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .left {
        .expiring-badge {
          margin-top: -2px;
          margin-left: 2px;
        }
      }

      .right {
        display: flex;
        align-items: center;
      }
    }

    .contract-expand {
      padding: 20px;
      
      .el-form-item {
        margin-right: 20px;
        margin-bottom: 0;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .attachment-list {
    .attachment-item {
      display: flex;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #EBEEF5;

      &:last-child {
        border-bottom: none;
      }

      i {
        color: #909399;
        margin-right: 8px;
      }

      .file-name {
        flex: 1;
        color: #606266;
      }

      .el-button {
        margin-left: 10px;
      }
    }
  }

  .remark-text {
    color: #606266;
    line-height: 1.6;
    margin: 0;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  :deep(.el-timeline-item__node) {
    &.el-timeline-item__node--normal {
      left: -2px;
      width: 12px;
      height: 12px;
    }
  }

  .contract-upload {
    :deep(.el-upload-list__item) {
      transition: all 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }

  .preview-dialog {
    :deep(.el-dialog__body) {
      padding: 0;
    }

    .preview-container {
      height: 70vh;
      
      iframe {
        width: 100%;
        height: 100%;
      }
    }
  }

  .contract-statistics {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 20px;

    .stat-card {
      background: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
      text-align: center;

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #409EFF;
        margin: 10px 0;
      }

      .stat-label {
        color: #909399;
        font-size: 14px;
      }

      &.warning {
        .stat-value {
          color: #E6A23C;
        }
      }

      &.danger {
        .stat-value {
          color: #F56C6C;
        }
      }
    }
  }

  .contract-timeline {
    margin-top: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);

    .timeline-title {
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  .file-preview {
    border: 1px solid #EBEEF5;
    border-radius: 4px;
    padding: 20px;
    margin-top: 10px;
    
    .preview-toolbar {
      margin-bottom: 10px;
      text-align: right;
    }
  }
}
</style> 